package spring.aop;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author bin.zhang
 * @version 2017年9月8日 上午10:09:48
 */
public class Client {

    public static void main(String[] args) {

        System.out.println("-----------方式一-----------");

        System.out.println("测试CGLibProxy:");
        UserManager userManager = (UserManager) new CGLibProxy().createProxyObject(new UserManagerImpl());
        userManager.addUser("Kobe", "24");

        System.out.println("测试JDKProxy:");
        JDKProxy jdkPrpxy = new JDKProxy();
        UserManager userManagerJDK = (UserManager) jdkPrpxy.newProxy(new UserManagerImpl());
        userManagerJDK.addUser("LeBron", "23");
        System.out.println("\n\n");

        System.out.println("-----------方式二-----------");

        final UserManagerImpl umi = new UserManagerImpl();

        System.out.println("测试CGLibProxy:");
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(umi.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) throws Throwable {
                System.out.println("start cglib proxy...");
                Object rst = arg1.invoke(umi, arg2);
                System.out.println("end cglib proxy...");
                return rst;
            }
        });
        UserManager objCglib = (UserManager) enhancer.create();
        System.out.println(objCglib.addUser("tim", "duck"));

        System.out.println("测试JDKProxy:");
        UserManager obj = (UserManager) Proxy.newProxyInstance(umi.getClass().getClassLoader(), umi.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("start jdk proxy...");
                Object rst = method.invoke(umi, args);
                System.out.println("end jdk proxy...");
                return rst;
            }
        });
        System.out.println(obj.addUser("tom", "root"));
    }

}
